<?php
namespace app\client\controller;
use app\common\lib\Redis;
use think\swoole\facade\Task;
use app\client\lib\SMS;

class Merchant extends Base {
    
    const fansNumber = 30;
    
    public function __construct() {
        parent::__construct();
    }
    
    
    private function _vailPerson($name, $idcard) {
        $ch = curl_init('https://op.juhe.cn/idcard/query');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['key' => 'c0e777f240ddcea02ca8294b7af47eb2', 'realname' => $name, 'idcard' => $idcard]));
        $result = curl_exec($ch);
        curl_close($ch);
        if(empty($result)) {
            return false;
        }
        $result = json_decode($result, true);
        if(empty($result)) {
            return false;
        }
        
        if($result['error_code'] !== 0) {
            return false;
        }
        
        if($result['result']['res'] != 1) {
            return false;
        }
        return true;
    }
    
    public function apply() {
        $params = request()->post();
        
        $code = isset($params['smsCode']) ? trim($params['smsCode']) : '';
        if($code === '') {
            return errorResult('请填写短信验证码');
        }
        
        
        $mobile = isset($params['mobile']) ? trim(htmlspecialchars($params['mobile'])) : '';
        
        $sms = new SMS($mobile);
        if(!$sms->validate('sms_merchant_apply_' . $this->userid, $code)) {
            return errorResult('验证码错误');
        }
        
        $type = isset($params['type']) ? trim(htmlspecialchars($params['type'])) : 1;
        if($type != 1 && $type != 2) {
            return errorResult();
        }
        $data['oper_name'] = isset($params['operName']) ? trim(htmlspecialchars($params['operName'])) : '';
        $data['idcard'] = isset($params['idcard']) ? trim(htmlspecialchars($params['idcard'])) : '';
        $data['idcard_picture_1'] = isset($params['idcardImg1']) ? trim(htmlspecialchars($params['idcardImg1'])) : '';
        $data['idcard_picture_2'] = isset($params['idcardImg2']) ? trim(htmlspecialchars($params['idcardImg2'])) : '';
        $data['merchant_name'] = isset($params['merchantName']) ? trim(htmlspecialchars($params['merchantName'])) : '';
        $data['address'] = isset($params['address']) ? trim(htmlspecialchars($params['address'])) : '';
        $data['license_code'] = isset($params['licenseCode']) ? trim(htmlspecialchars($params['licenseCode'])) : '';
        $data['license_picture'] = isset($params['licenseImg']) ? trim(htmlspecialchars($params['licenseImg'])) : '';
        $data['store_picture_1'] = isset($params['storeImg']) ? trim(htmlspecialchars($params['storeImg'])) : '';
        $data['store_picture_2'] = isset($params['storeInnerImg']) ? trim(htmlspecialchars($params['storeInnerImg'])) : '';
        $data['mobile'] = $mobile;
        $data['user_id'] = $this->userid;
        $data['amount'] = 300;
        

        if($type == 1) { //企业认证
            //$ch = curl_init('https://japi.juhe.cn/enterprise/simpleList?key=' . $juheKey . '&keyword=' . $data['license_code']);
            $ch = curl_init('https://japi.juhe.cn/enterprise/simpleList');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['key' => 'b79f973c619305501e60a00cdc57b902', 'keyword' => $data['license_code']]));
            $result = curl_exec($ch);
            curl_close($ch);
            
            
            Task::async(function() use($result) {
                var_dump($result);
            });
            
            if(empty($result)) {
                return errorResult();
            }
            $result = json_decode($result, true);
            if(empty($result)) {
                return errorResult();
            }
            
            if($result['error_code'] !== 0) {
                return errorResult('企业认证失败');
             }
             $vail = false;
             $items = $result['result']['data']['items'];
             foreach ($items as $item) {
                 if($item['oper_name'] == $data['oper_name']) {
                     $vail = true;
                     break;
                }
             }
             
             if(!$vail) {
                return errorResult('企业认证失败');
             }
             
             
             if(!$this->_vailPerson($data['oper_name'], $data['idcard'])) {
                 return errorResult('企业认证失败');
             }
             
             
        }else {
            $number = model('FollowUser')->where(['user_id' => $this->userid])->count();
            if($number < self::fansNumber) {
                return errorResult('粉丝数不达标');
            }
            
            
            if(!$this->_vailPerson($data['oper_name'], $data['idcard'])) {
                return errorResult('身份证认证失败');
            }
            
            
            
        }
        
        $data['type'] = $type;
        
        
        $orderNo = getOrderNo($this->userid);
        
        $data['order_no'] = $orderNo;
        $data['create_time'] = time();
        
        $rs = model('ApplyMerchant')->add($data);
        if(!$rs) {
            return errorResult();
        }
        
        return successResult(['order_no' => $orderNo, 'amount' => 1000, 'fee' => 288]);
    }
    
    public function pay() {
        $orderNo = request()->post('no', '');
        if(empty($orderNo)) {
            return errorResult();
        }
        
        $order = model('ApplyMerchant')->findOne(['order_no' => $orderNo], ['amount', 'user_id']);
        if(empty($order) || $order['user_id'] != $this->userid) {
            return errorResult();
        }
        
        //发起支付
        $wxPay = new \app\client\wxpay\WxPayUnifiedOrder(session('user')['openid']);
        $wxPay->setOrder([
            'body' => '测试的支付',
            'order_no' => $orderNo,
            'amount' => $order['amount'],
            'notify_url' => 'merchatApplyNotify'
        ]);
        
        $payParams = $wxPay->getParams(); //获取发起支付的参数
        
        if($payParams['err']){
            return errorResult('abc');
        }
        
        return successResult(['wxparam' => $payParams['params']]);
    }
    
    public function setPayType() {
        $params = request()->post();
        
        $data['wx_pay'] = isset($params['wx_pay']) ? trim(htmlspecialchars($params['wx_pay'])) : '';
        $data['ali_pay'] = isset($params['ali_pay']) ? trim(htmlspecialchars($params['ali_pay'])) : '';
        
        $data['bank_user'] = isset($params['bank_user']) ? trim(htmlspecialchars($params['bank_user'])) : '';
        $data['bank_account'] = isset($params['bank_account']) ? trim(htmlspecialchars($params['bank_account'])) : '';
        $data['bank_name'] = isset($params['bank_name']) ? trim(htmlspecialchars($params['bank_name'])) : '';
        
        if($data['wx_pay'] === '' && $data['ali_pay']){
            return errorResult('至少设置一种扫码支付方式');
        }

        
        $where = ['user_id' => $this->userid];
        $model = model('PayType');
        
        $result = $model->findOne($where, array_keys($data));
        
        if(empty($result)){ //还没设置
            $data['user_id'] = $this->userid;
            $rs = $model->add($data);
            if($rs){
                return successResult('设置成功');
            }
            return errorResult('设置失败');
        }
        
        $update = [];
        
        foreach ($data as $k => $val) {
            if($val !== $result[$k]){
                $update[$k] = $val;
            }
        }
        
        if(!empty($update)){
            $rs = $model->modify($where, $update);
            if(!$rs){
                return errorResult('设置失败');
            }
        }
        
        return successResult('设置成功');
    }
    
    public function getPayType() {
        $result = model('PayType')->findOne(['user_id' => $this->userid], ['wx_pay', 'ali_pay', 'bank_user', 'bank_account', 'bank_name']);
        return successResult($result);
    }
    
    public function personApplyFansNumber() {
        return successResult(['number' => self::fansNumber]);
    }

}
